<template>
  <div class="container" style="padding: 0 10px">
    <div class="flex_js p_10_0">
      <div
        class="top_title"
        @click="
          ;(show_rule_table = !show_rule_table),
            EventBus.emit('show_rule_table')
        "
      >
        规则列表
        <img
          src="@/assets/img/menu_icon_right.png"
          style="width: 14px; height: 14px; margin-left: 5px"
          alt=""
          :class="show_rule_table ? 'select_me' : ''"
        />
      </div>
      <div class="flex">
        <el-input
          v-model="page_data.name"
          placeholder="请输入规则名称"
        ></el-input>
        <el-button @click="get_list()">搜索</el-button>
        <el-button @click=";(page_data.name = ''), get_list()">重置</el-button>
      </div>
      <div class="flex">
        <el-button
          type="primary"
          @click="show_box = true"
          v-if="
            has_role_list[0].has_role &&
            store.state.current_enterprise_level.some((i) => {
              return i.productId == '2' && ['3', '4'].includes(i.levelId)
            })
          "
          >新增</el-button
        >
        <setTable
          :data="header_list"
          :height_size="height_size"
          @changeShowTable="
            (e) => {
              header_list[e].showTable = !header_list[e].showTable
            }
          "
          @resetTableSet="
            () => {
              header_list.forEach((item) => {
                item.showTable = true
              })
            }
          "
          @changeHeightSize="
            (e) => {
              height_size = e
            }
          "
        ></setTable>
      </div>
    </div>
    <div v-show="show_rule_table">
      <el-table
        :data="list"
        border
        ref="table"
        class="tc"
        :max-height="max_height"
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: 'sort', order: 'ascending' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
        :row-class-name="
          ({ row, rowIndex }) => {
            row.index = rowIndex
          }
        "
        @row-click="
          (row) => {
            get_list_info(row)
          }
        "
      >
        <el-table-column
          label="序号"
          type="index"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="规则名称"
          sortable
          prop="name"
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          :label="rule_type == 1 ? '模板类型' : '配件类型'"
          sortable
          prop="identifierTemplateList"
          v-if="header_list[1].showTable"
        >
          <template #default="scope: any">
            <span
              style="margin-right: 5px"
              v-for="item in scope.row.identifierTemplateList"
            >
              {{ item.templateName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          prop="sort"
          width="60px"
          v-if="header_list[2].showTable"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="160px"
          v-if="
            has_role_list[0].has_role &&
            store.state.current_enterprise_level.some((i) => {
              return i.productId == '2' && ['3', '4'].includes(i.levelId)
            })
          "
        >
          <template #default="scope: any">
            <div class="flex_cc" style="column-gap: 20px">
              <el-tooltip content="编辑" placement="bottom">
                <svgBtn
                  icon="table_edit"
                  style="font-size: 20px"
                  @click="edit_list(scope.row)"
                ></svgBtn>
              </el-tooltip>
              <el-tooltip content="删除" placement="bottom">
                <svgBtn
                  icon="table_delete"
                  style="font-size: 20px"
                  @click="delete_list({ item: scope.row, type: 0 })"
                ></svgBtn>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    size="50%"
    destroy-on-close
    :close-on-click-modal="false"
    @close="resetForm(addrolelistform)"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增规则</h4>
      <h4 v-else>编辑规则</h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        ref="addrolelistform"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.name"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="适用模板类型" prop="type_list">
          <el-cascader
            :options="mould_list"
            :props="props_cascader"
            v-model="add_form_data.type_list"
            clearable
            filterable
            :show-all-levels="false"
            style="width: 100%"
            ref="tree"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.sort"
            show-word-limit
            maxlength="3"
          ></el-input>
        </el-form-item>
        <div class="tr m_top10">
          <el-button @click="resetForm(addrolelistform)">取消</el-button>
          <el-button
            type="primary"
            @click="submit(addrolelistform)"
            :loading="btn_loading"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
  <dialog_box
    @submit_delete="submit_delete"
    @close="show_delete_box = false"
    :delete_name="delete_name"
    :show_delete_box="show_delete_box"
    :delete_box_status="delete_box_status"
  ></dialog_box>
</template>

<script lang="ts" setup>
import { check_role, debounce } from '@/utils/check_role' // 权限校验
import dialog_box from '@/view/components/dialog_box.vue'
import svgBtn from '@/components/svg_button.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, nextTick, computed } from 'vue'
import { FormInstance, ElMessage } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
const store = useStore()
// type FormInstance = InstanceType<typeof ElForm>
const addrolelistform = ref<FormInstance>()
const rules = ref({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type_list: [{ required: true, message: '请选择模板', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
})
const height_size = ref(1)
const header_list = ref([
  {
    label: '规则名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '模板类型',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '排序',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const show_box = ref(false)
const page_data = ref({
  current: 1,
  pageSize: 10,
  name: '',
  type: computed(() => {
    return props.rule_type
  }),
})
const list = ref()
const total = ref()
const props = defineProps({
  rule_type: Number,
})
// 页面权限组 三个组件通用
const has_role_list = ref(
  props.rule_type == 1
    ? [{ path: 'mouldIdentifier/post', has_role: false }]
    : props.rule_type == 2
    ? [{ path: 'partsIdentifier/post', has_role: false }]
    : [{ path: 'partsselfIdentifier/post', has_role: false }]
)
const add_form_data = ref({
  id: '',
  name: '',
  type_list: [],
  identifierTemplate: [],
  sort: '',
  type: computed(() => {
    return props.rule_type
  }),
})
const currentRowIndex = ref(0)
const get_list_info = (e) => {
  console.log(e)
  EventBus.emit('rule_id', {
    id: e.id,
    templateId_list: e.identifierTemplateList,
  })
}
const show_rule_table = ref(true)
onMounted(() => {
  show_rule_table.value = true
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  EventBus.on('show_num_table', () => {
    show_rule_table.value = !show_rule_table.value
  })
  get_list()
  get_mould_list()
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item)
  })
})
onUnmounted(() => {
  EventBus.off('refresh')
  EventBus.off('show_num_table')
})
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 350 // 不带分页的 table 高度
})
const edit_list = (e) => {
  add_form_data.value = {
    id: e.id,
    name: e.name,
    sort: e.sort,
    type_list: [],
    identifierTemplate: [],
    type: add_form_data.value.type,
  }
  if (e.identifierTemplateList.length) {
    e.identifierTemplateList.forEach((item) => {
      add_form_data.value.type_list.push(item.templateId)
    })
  }
  show_box.value = true
}
const show_delete_box = ref(false)
const delete_box_status = ref()
const delete_id = ref()
const delete_name = ref()
const delete_list = (e) => {
  console.log(e)
  delete_box_status.value = e.type
  show_delete_box.value = true
  delete_id.value = e.item.id
  delete_name.value = e.item.name
}
const submit_delete = () => {
  axios
    .request({
      url: serviceApi.rule_crud + '/' + delete_id.value,
      method: 'delete',
    })
    .then((res) => {
      console.log(res)
      ElMessage.success('删除成功！')
      show_delete_box.value = false
      get_list()
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      add_form_data.value.type_list.forEach((item) => {
        add_form_data.value.identifierTemplate.push({
          templateId: Array.isArray(item) ? item[1] : item,
        })
      })
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.rule_crud
              : serviceApi.rule_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'POST' : 'PUT',
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          btn_loading.value = false
          get_list()
          resetForm(formEl)
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    }
  })
}
const loading = ref(false)
const table = ref(null)
const get_list = () => {
  if (loading.value) return
  loading.value = true
  axios
    .request({
      url: serviceApi.rule_list,
      method: 'POST',
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      if (res.data.content.length) {
        table.value.setCurrentRow(res.data.content[currentRowIndex.value])
        get_list_info(res.data.content[currentRowIndex.value])
      }
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((err) => {
      loading.value = false
      ElMessage.error(err)
    })
}

let list_debounce = debounce(200, get_list)
const mould_list = ref([])
const props_cascader = { multiple: true }
const get_mould_list = () => {
  axios
    .request({
      url: serviceApi.template_list + '?type=' + (props.rule_type != 3 ? 1 : 2),
      method: 'post',
    })
    .then((res) => {
      console.log(res)
      // 转 二级树
      mould_list.value = arrToTree(res.data.reverse())
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const arrToTree = (res_list) => {
  var list_1 = []
  for (let i in res_list) {
    if (res_list[i].isLimitEnterprise) {
      res_list[i].label = res_list[i].name + '（特殊开放）'
    } else {
      res_list[i].label = res_list[i].name
    }
    res_list[i].value = res_list[i].id
    res_list[i].parentId == null ? (res_list[i].parentId = -1) : ''
    if (res_list[i].parentId == -1) {
      res_list[i].children = []
      list_1.push(res_list[i])
    }
  }
  for (let i in res_list) {
    for (let ii in list_1) {
      if (list_1[ii].id == res_list[i].parentId) {
        list_1[ii].children.push(res_list[i])
        list_1[ii].children.sort(function (a, b) {
          return a.sort - b.sort
        })
      }
    }
  }
  return list_1
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    type_list: [],
    identifierTemplate: [],
    sort: '',
    type: add_form_data.value.type,
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped>
.top_title {
  display: flex;
  align-items: center;
  padding: 2px 5px;
  border: 1px solid #666;
  border-radius: 10px;
  color: #666;
  cursor: pointer;
  &:hover {
    border-color: #3580eb;
    color: #3580eb;
  }
}
.select_me {
  transform: rotate(90deg);
}
</style>
